const RequestController = require("../../controller/request")

const xhs_sign = require("./xhs_sign")

const api_host = 'https://edith.xiaohongshu.com'

const common_headers = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
    "cache-control": "no-cache",
    "content-type": "application/json;charset=UTF-8",
    "dnt": "1",
    "origin": "https://www.xiaohongshu.com",
    "pragma": "no-cache",
    "priority": "u=1, i",
    "referer": "https://www.xiaohongshu.com/",
    "sec-ch-ua": '"Google Chrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-site",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
}

async function xhsRemote(uri, params, headers, need_sign = true, post = true) {
    const requestController = new RequestController()
    Object.assign(headers, common_headers)

    let response;

    if (post) {
        if (need_sign) {
            // 加密请求头
            // const sign_header = await xhs_sign({uri: uri, params: params, headers: headers['cookie']})
            const sign_header = xhs_sign.sign(uri, params, headers['cookie'])
            Object.assign(headers, sign_header)
        }
        response = await requestController.node_request({
            url: `${api_host}${uri}`,
            method: "POST",
            data: JSON.stringify(params),
            headers: headers
        })
    } else {
        if (params?.image_formats) params.image_formats = params.image_formats.join(',')
        if (params) {
            const query = Object.entries(params)
                .map(([key, value]) => `${key}=${Array.isArray(value)? value.join(',') : value}`)
                .join('&');
        }
        if (need_sign) {
            // 加密请求头
            const sign_header = xhs_sign.sign(`${uri}?${query}`, null, headers['cookie'])
            // const sign_header = await xhs_sign({uri: `${uri}?${query}`, params: null, headers: headers['cookie']})
            Object.assign(headers, sign_header)
        }
        response = await requestController.node_request({
            url: `${api_host}${uri}?${query}`,
            method: "GET",
            headers: headers
        })
    }
    return response
}

module.exports = {xhsRemote}